<template>
  <div class="planning-container">
    <el-card>
      <div class="management-title">
        <h2>小区规划 - {{ plotName }}</h2>
        <el-button @click="goBack" style="margin-left: 16px;">返回楼栋列表</el-button>
      </div>

      <!-- 小区信息展示 -->
      <div class="plot-info-section" v-if="plotInfo.name">
        <div class="plot-info-card">
          <div class="plot-info-left">
            <div class="plot-info-images" v-if="plotImages.length > 0">
              <img
                v-for="(image, index) in plotImages.slice(0, 3)"
                :key="index"
                :src="image"
                :alt="`小区图片${index + 1}`"
                class="plot-info-img"
                @error="handleImageError"
              />
            </div>
            <div v-else class="no-images">
              <el-icon size="48"><Picture /></el-icon>
              <p>暂无图片</p>
            </div>
          </div>

          <div class="plot-info-right">
            <h3 class="plot-info-title">{{ plotInfo.name }}</h3>
            <div class="plot-info-details">
              <div class="info-item">
                <el-icon><LocationFilled /></el-icon>
                <span>{{ plotInfo.address || '地址信息暂无' }}</span>
              </div>
              <div class="info-item" v-if="plotInfo.number">
                <el-icon><Phone /></el-icon>
                <span>{{ plotInfo.number }}</span>
              </div>
              <div class="info-item" v-if="plotInfo.listTime">
                <el-icon><Calendar /></el-icon>
                <span>开盘时间：{{ formatDate(plotInfo.listTime) }}</span>
              </div>
              <div class="info-item">
                <el-icon><OfficeBuilding /></el-icon>
                <span>楼栋总数：{{ buildingList.length }}栋</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="building-header">
        <div class="header-left">
          <el-button type="primary" @click="handleAddBuilding">
            <el-icon><Plus /></el-icon>
            新增楼栋
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedIds.length }})
          </el-button>
        </div>
        <div class="header-right">
          <span class="building-count">共 {{ buildingList.length }} 栋楼栋</span>
        </div>
      </div>

      <!-- 楼栋列表表格 -->
      <div class="building-table-section">
        <el-table
          :data="buildingList"
          v-loading="loading"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="楼栋名称" min-width="100">
            <template #default="{ row }">
              {{ row.name }}栋
            </template>
          </el-table-column>
          <el-table-column prop="unitNum" label="单元数" min-width="80" align="center">
            <template #default="{ row }">
              {{ row.unitNum }}个
            </template>
          </el-table-column>
          <el-table-column prop="floorNum" label="楼层数" min-width="80" align="center">
            <template #default="{ row }">
              {{ row.floorNum }}层
            </template>
          </el-table-column>
          <el-table-column prop="totalHouses" label="房屋总数" min-width="100" align="center">
            <template #default="{ row }">
              {{ row.totalHouses || row.houseNum || 0 }}套
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="handleViewDetails(row)">
                房源详情
              </el-button>
              <el-button size="small" type="success" @click="handleManageTypes(row)">
                户型管理
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="!loading && buildingList.length === 0" class="empty-state">
          <el-empty description="该小区暂无楼栋数据">
            <el-button type="primary" @click="handleAddBuilding">添加楼栋</el-button>
          </el-empty>
        </div>
      </div>
    </el-card>

    <!-- 添加楼栋对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="添加楼栋"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="buildingFormRef"
        :model="buildingForm"
        :rules="buildingFormRules"
        label-width="120px"
      >
        <el-form-item label="楼栋名称" prop="name">
          <el-input
            v-model="buildingForm.name"
            placeholder="请输入楼栋名称，如：1、A、甲等"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="单元数" prop="unitNum">
          <el-input-number
            v-model="buildingForm.unitNum"
            :min="1"
            :max="20"
            @change="handleUnitNumChange"
          />
          <span class="form-tip">每栋楼的单元数量</span>
        </el-form-item>

        <el-form-item label="层数" prop="floorNum">
          <el-input-number
            v-model="buildingForm.floorNum"
            :min="1"
            :max="100"
          />
          <span class="form-tip">每个单元的层数</span>
        </el-form-item>

        <el-form-item label="每单元每层户数">
          <div class="floor-user-config">
            <div
              v-for="(userNum, index) in buildingForm.floorUserNumList"
              :key="index"
              class="unit-config"
            >
              <span class="unit-label">第{{ index + 1 }}单元：</span>
              <el-input-number
                v-model="buildingForm.floorUserNumList[index]"
                :min="1"
                :max="20"
                size="small"
              />
              <span class="unit-suffix">户/层</span>
            </div>
          </div>
          <div class="form-tip">设置每个单元每层的户数</div>
        </el-form-item>

        <el-form-item label="预计房屋总数">
          <el-input :value="calculateTotalHouses() + '套'" readonly />
          <div class="form-tip">根据上述配置自动计算</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelAdd">取消</el-button>
          <el-button type="primary" @click="handleConfirmAdd" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import { Plus, Delete, Picture, UploadFilled, LocationFilled, Phone, Calendar, OfficeBuilding } from '@element-plus/icons-vue';
import baseService from "@/service/baseService";

// 响应式数据
const loading = ref(false);
const buildingList = ref<any[]>([]);
const plotInfo = ref<any>({});
const plotImages = ref([]);
const selectedIds = ref<any[]>([]);

// 新增楼栋相关
const showAddDialog = ref(false);
const submitLoading = ref(false);
const buildingFormRef = ref();

// 楼栋表单数据
const buildingForm = reactive({
  name: '',
  unitNum: 1,
  floorNum: 1,
  floorUserNumList: [1]
});

// 表单验证规则
const buildingFormRules = {
  name: [
    { required: true, message: '请输入楼栋名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  unitNum: [
    { required: true, message: '请输入单元数', trigger: 'blur' }
  ],
  floorNum: [
    { required: true, message: '请输入楼层数', trigger: 'blur' }
  ]
};

// 获取URL参数（兼容hash模式）
const getUrlParams = () => {
  const hash = window.location.hash;
  const queryString = hash.includes('?') ? hash.split('?')[1] : window.location.search.substring(1);
  return new URLSearchParams(queryString);
};

const urlParams = getUrlParams();
const plotId = ref(urlParams.get('plotId') || '');
const plotName = ref(decodeURIComponent(urlParams.get('plotName') || ''));
const plotAddress = ref(decodeURIComponent(urlParams.get('plotAddress') || ''));

// 处理小区图片
const processPlotImages = (plot: any) => {
  if (plot.ossUrls) {
    plotImages.value = plot.ossUrls.split(',').filter((url: string) => url.trim());
  } else {
    plotImages.value = [];
  }
};

// 工具函数
const formatDate = (dateStr: string) => {
  if (!dateStr) return '暂无';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.src = '';
};

// 事件处理函数
const goBack = () => {
  window.close();
};

const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id);
};

const handleViewDetails = (building: any) => {
  // 跳转到房源详情页面
  const url = `#/rental/house-list-details?buildingId=${building.id}&buildingName=${encodeURIComponent(building.name)}&plotName=${encodeURIComponent(plotName.value)}`;
  window.open(url, '_blank');
};

const handleManageTypes = (building: any) => {
  // 跳转到户型管理页面
  const url = `#/rental/type-management?buildingId=${building.id}&buildingName=${encodeURIComponent(building.name)}栋&plotName=${encodeURIComponent(plotName.value)}`;
  window.open(url, '_blank');
};

const handleAddBuilding = () => {
  showAddDialog.value = true;
  resetBuildingForm();
};

// 删除楼栋API（强制物理删除）
const deleteBuildingData = async (ids: any[]) => {
  try {
    // 确保IDs是数字数组
    const numericIds = ids.map(id => parseInt(id.toString()));
    console.log('删除楼栋IDs:', numericIds);

    // 先尝试逻辑删除，再物理删除，确保彻底删除
    try {
      console.log('第一步：逻辑删除');
      await baseService.delete('/rental/areabuilding/logicDelete', numericIds);
    } catch (error) {
      console.log('逻辑删除失败或已删除:', error);
    }

    console.log('第二步：物理删除');
    // 直接调用数据库删除，不管逻辑删除状态
    const response = await baseService.delete('/rental/areabuilding/forceDelete', numericIds);

    console.log('删除响应:', response);

    if (response.code === 0) {
      ElMessage.success('删除成功');
      return true;
    } else {
      // 如果没有forceDelete接口，尝试普通删除
      console.log('尝试普通删除接口');
      const response2 = await baseService.delete('/rental/areabuilding', numericIds);
      if (response2.code === 0) {
        ElMessage.success('删除成功');
        return true;
      } else {
        ElMessage.error(response2.msg || '删除失败');
        return false;
      }
    }
  } catch (error) {
    console.error('删除楼栋失败:', error);
    ElMessage.error('删除楼栋失败，请检查网络连接');
    return false;
  }
};

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的楼栋');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 栋楼栋吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const success = await deleteBuildingData(selectedIds.value);
    if (success) {
      selectedIds.value = [];
      getBuildingList(); // 重新获取列表
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

// 保存楼栋API
const saveBuildingData = async (data: any) => {
  try {
    console.log('请求数据:', data);
    console.log('请求URL:', '/rental/areabuilding');

    const response = await baseService.post('/rental/areabuilding', data, {
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });

    console.log('保存响应:', response);

    if (response.code === 0) {
      ElMessage.success('楼栋添加成功');
      return true;
    } else {
      ElMessage.error(response.msg || '添加楼栋失败');
      return false;
    }
  } catch (error) {
    console.error('保存楼栋失败:', error);
    ElMessage.error('保存楼栋失败，请检查网络连接');
    return false;
  }
};

// 表单处理方法
const resetBuildingForm = () => {
  buildingForm.name = '';
  buildingForm.unitNum = 1;
  buildingForm.floorNum = 1;
  buildingForm.floorUserNumList = [1];
  if (buildingFormRef.value) {
    buildingFormRef.value.clearValidate();
  }
};

const handleUnitNumChange = (value: number) => {
  const currentLength = buildingForm.floorUserNumList.length;
  if (value > currentLength) {
    // 增加单元，默认每层1户
    for (let i = currentLength; i < value; i++) {
      buildingForm.floorUserNumList.push(1);
    }
  } else if (value < currentLength) {
    // 减少单元
    buildingForm.floorUserNumList = buildingForm.floorUserNumList.slice(0, value);
  }
};

const calculateTotalHouses = () => {
  return buildingForm.floorUserNumList.reduce((sum, userNum) => sum + userNum * buildingForm.floorNum, 0);
};

const handleConfirmAdd = async () => {
  if (!buildingFormRef.value) return;

  try {
    await buildingFormRef.value.validate();

    submitLoading.value = true;

    const buildingData = {
      name: buildingForm.name,
      plotId: parseInt(plotId.value || '0'),
      unitNum: buildingForm.unitNum,
      floorNum: buildingForm.floorNum,
      floorUserNumList: [...buildingForm.floorUserNumList]
    };

    console.log('提交楼栋数据:', buildingData);

    const success = await saveBuildingData(buildingData);
    if (success) {
      showAddDialog.value = false;
      resetBuildingForm();
      getBuildingList(); // 重新获取楼栋列表
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

const handleCancelAdd = () => {
  showAddDialog.value = false;
  resetBuildingForm();
};

// API调用函数
const getPlotInfo = async () => {
  try {
    const response = await baseService.get(`/rental/areaplot/${plotId.value}`);
    if (response.code === 0) {
      plotInfo.value = response.data || {};
      processPlotImages(plotInfo.value);
    }
  } catch (error) {
    console.error('获取小区信息失败:', error);
  }
};

const getBuildingList = async () => {
  loading.value = true;
  try {
    const response = await baseService.get(`/rental/areabuilding/getBuildingByPlotId/${plotId.value}`);
    if (response.code === 0) {
      buildingList.value = response.data.list || [];
      ElMessage.success(`成功获取 ${buildingList.value.length} 栋楼栋数据`);
    } else {
      ElMessage.error(response.msg || '获取楼栋列表失败');
    }
  } catch (error) {
    console.error('获取楼栋列表失败:', error);
    ElMessage.error('获取楼栋列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  if (!plotId.value) {
    ElMessage.error('缺少小区ID参数');
    return;
  }
  getPlotInfo();
  getBuildingList();
});
</script>

<style scoped>
.planning-container {
  display: flex;
  flex-direction: column;
}

.management-title {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.management-title h2 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.plot-info-section {
  margin-bottom: 24px;
}

.building-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 12px;
}

.header-right {
  color: #606266;
  font-size: 14px;
}

.building-count {
  font-weight: 500;
}

.building-table-section {
  margin-top: 16px;
}

.empty-state {
  margin-top: 40px;
}

/* 表单样式 */
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}

.floor-user-config {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.unit-config {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-label {
  min-width: 80px;
  color: #606266;
  font-size: 14px;
}

.unit-suffix {
  color: #909399;
  font-size: 12px;
}

.plot-info-card {
  display: flex;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

.plot-info-left {
  width: 200px;
  margin-right: 20px;
  flex-shrink: 0;
}

.plot-info-images {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.plot-info-img {
  width: 60px;
  height: 45px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
}

.no-images {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #909399;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px dashed #dcdfe6;
}

.no-images p {
  margin: 8px 0 0 0;
  font-size: 12px;
}

.plot-info-right {
  flex: 1;
}

.plot-info-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
}

.plot-info-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.info-item .el-icon {
  color: #409eff;
}

.planning-header {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.planning-content {
  min-height: 400px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  background: #fafafa;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.upload-hint {
  color: #909399;
  font-size: 12px;
}

.planning-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 20px;
}

.planning-image-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.planning-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.planning-image-item:hover .image-overlay {
  opacity: 1;
}

.image-actions {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .planning-images {
    grid-template-columns: 1fr;
  }

  .plot-info-card {
    flex-direction: column;
  }

  .plot-info-left {
    width: 100%;
    margin-right: 0;
    margin-bottom: 16px;
  }

  .management-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
